<template>
  <div :class="{'editor': !readonly}" class="table_datetime" @mouseenter="editVisible = true" @mouseleave.stop="editVisible = false">
    <input :value="(value !== '' && value !== null) ? moment(value, valueFormat.replace('dd', 'DD')).format(format.replace('dd', 'DD')): null" :readonly="true"/>
    <a-date-picker :value="(value !== '' && value !== null) ? moment(value, valueFormat.replace('dd', 'DD')).format(format.replace('dd', 'DD')): null" :show-time="showTime" @ok="handleOk" @change="handleChange" @openChange="handleDateChange" :locale="locale" style="min-width: 20px; width: 20px; height: 30px">
      <span style="line-height: 30px">
        <a-icon type="calendar" v-if="editor" v-show="editVisible" @click.stop="editorClick"/>
      </span>
    </a-date-picker>
  </div>
</template>

<script>
import { 
  updateRow
} from "@/api/worksheet";
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import moment from 'moment';
export default {
	props: {
		value: {
			default: ""
		},
		editor: {
			default: true
		},
    rowId: String,
    fieldName: String,
    format: String,
    valueFormat: String,
	},
	data(){
		return{
			editVisible: false,
			readonly: true,
			showTime: true,
			moment,
      locale
		}
	},
	methods:{
    editorClick(){
        this.readonly = false
    },
    async handleOk(date){
      this.value = moment(date).format(this.valueFormat.replace('dd', 'DD'))
      await updateRow({worksheetId: this.worksheetId, data: {[this.fieldName]: this.value}, rowId: this.rowId})
    },
    handleDateChange(status){
      if(!status){
        this.readonly = true
      }
    },
    async handleChange(date){
      if(!this.showTime){
        this.value = moment(date).format(this.valueFormat.replace('dd', 'DD'))
        await updateRow({worksheetId: this.worksheetId, data: {[this.fieldName]: this.value}, rowId: this.rowId})
      }
    }
	},
  computed:{
      worksheetId() {
          return this.$route.params.worksheetId;
      }
  },
  mounted(){
      this.showTime = this.valueFormat.includes('H')
  }
}

</script>

<style lang="less">
.appPage{
  .table_datetime{
      padding: 0 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      overflow: hidden;
      text-overflow: ellipsis;
      input{
        color: #606266 !important;
        border: none !important;
        width: 95%;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      i{
        cursor: pointer;
        color: #606266;
      }
      i:hover{
        color: #0f8df2;
      }
  }
  .editor{
      border: 2px #0f8df2 solid;
      background-color: white;
  }
}
</style>